package com.zb.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;

import com.zb.common.utils.Constants;
import com.zb.common.utils.CookieUtil;
import com.zb.session.UmeiHttpServletRequestWrapper;

public class SessionFilter extends HttpServlet implements Filter {
    private final static String[] static_ext = { "js", "css", "jpg", "png",
            "gif", "html", "ico", "vm", "swf" };
    private static final long serialVersionUID = 8962825498342953698L;
    private Logger logger = org.slf4j.LoggerFactory
            .getLogger(SessionFilter.class);

    public void doFilter(ServletRequest servletRequest,
            ServletResponse servletResponse, FilterChain filterChain)
            throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String req_uri = request.getRequestURI();
        String type = req_uri.substring(req_uri.lastIndexOf('.') + 1);
        // 静态资源忽略
        if (ArrayUtils.contains(static_ext, type)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String sid = CookieUtil.getCookieValue(request, Constants.JSESSIONID);
        logger.info("cookie sid:" + sid);
        if (sid == null || sid.length() != 36) {// 没有cookie
            String url = request.getRequestURL().toString();
            logger.info("url:" + url);
            // 写cookie
            sid = java.util.UUID.randomUUID().toString();
        }
        CookieUtil.setCookie(response, Constants.JSESSIONID, sid);
        filterChain.doFilter(new UmeiHttpServletRequestWrapper(sid, request,
                response), response);

    }

    public void init(FilterConfig filterConfig) throws ServletException {

    }
}